<?php

namespace yifang\lib;
use yifang\App;
use Throwable;
use yifang\event\HttpRun;
use yifang\event\RouteLoaded;
use yifang\event\HttpEnd;
use yifang\response\Response;
use yifang\exception\Handle;

class Http
{
    /**
     * @var App
     */
    protected $app;

    /**
     * 应用名称
     * @var string
     */
    protected $name;

    /**
     * 应用路径
     * @var string
     */
    protected $path;

    /**
     * 路由路径
     */
    protected $routePath=array();

    /**
     * 是否绑定应用
     * @var bool
     */
    protected $isBind = false;

    public function __construct(App $app)
    {
        $this->app = $app;
        $this->routePath[] = $this->app->getAppPath() . 'route' . DIRECTORY_SEPARATOR;
    }

    /**
     * 设置应用名称
     * @access public
     * @param string $name 应用名称
     * @return $this
     */
    public function name($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * 获取应用名称
     * @access public
     * @return string
     */
    public function getName()
    {
        return $this->name ?: '';
    }

    /**
     * 设置应用绑定
     * @access public
     * @param bool $bind 是否绑定
     * @return $this
     */
    public function setBind($bind = true)
    {
        $this->isBind = $bind;
        return $this;
    }

    /**
     * 是否绑定应用
     * @access public
     * @return bool
     */
    public function isBind()
    {
        return $this->isBind;
    }

    /**
     * 设置应用目录
     * @access public
     * @param string $path 应用目录
     * @return $this
     */
    public function path($path)
    {
        if (substr($path, -1) != DIRECTORY_SEPARATOR) {
            $path .= DIRECTORY_SEPARATOR;
        }
        $this->path = $path;
        return $this;
    }

    /**
     * 获取应用路径
     * @access public
     * @return string
     */
    public function getPath()
    {
        return $this->path ?: '';
    }

    /**
     * 获取路由目录
     */
    public function getRoutePath()
    {
        return $this->routePath;
    }

    /**
     * 设置路由目录
     */
    public function setRoutePath($path)
    {
        $this->routePath[] = $path;
    }

    /**
     * 执行应用程序
     * @access public
     * @param Request|null $request
     */
    public function run(Request $request = null)
    {
        //初始化
        $this->initialize();
        //自动创建request对象
        $request = $request ?? $this->app->make('request', [], true);
        $this->app->instance('request', $request);
        try {
            $response = $this->runWithRequest($request);
        } catch (Throwable $e) {
            $this->reportException($e);
            $response = $this->renderException($request, $e);
        }
        return $response;
    }

    /**
     * Report the exception to the exception handler.
     */
    protected function reportException(Throwable $e)
    {
        $this->app->make(Handle::class)->report($e);
    }

    /**
     * Render the exception to a response.
     */
    protected function renderException($request, Throwable $e)
    {
        return $this->app->make(Handle::class)->render($request, $e);
    }

    /**
     * 执行应用程序
     * @param Request $request
     * @return mixed
     */
    protected function runWithRequest(Request $request)
    {
        // 加载全局中间件
        $this->loadMiddleware();

        // 监听HttpRun
        $this->app->event->trigger(HttpRun::class);

        return $this->app->middleware->pipeline()->send($request)->then(function ($request) {
            return $this->dispatchToRoute($request);
        });
    }

    /**
     * 派遣路由
     */
    protected function dispatchToRoute($request)
    {
        $withRoute = $this->app->config->get('app.with_route', true) ? function () {
            $this->loadRoutes();
        } : null;
        return $this->app->route->dispatch($request, $withRoute);
    }

    /**
     * 加载路由
     * @access protected
     * @return void
     */
    protected function loadRoutes()
    {
        // 加载路由定义
        $routePaths = $this->getRoutePath();
        foreach($routePaths as $routePath){
            if (is_dir($routePath)) {
                $files = glob($routePath . '*.php');
                foreach ($files as $file) {
                    include_once $file;
                }
            }
        }
        //加载插件路由
        if(function_exists("pluginInit")){
            pluginInit();
        }
        $this->app->event->trigger(RouteLoaded::class);
    }

    /**
     * 加载全局中间件
     */
    protected function loadMiddleware($type="global")
    {
        $middleware=$this->app->getAppPath() . 'middleware.php';
        if (is_file($middleware)) {
            $this->app->middleware->import(include $middleware,$type);
        }
    }

    /**
     * HttpEnd
     */
    public function end(Response $response)
    {
        $this->app->event->trigger(HttpEnd::class, $response);

        //执行中间件
        $this->app->middleware->end($response);
    }

    /**
     * 初始化
     */
    protected function initialize()
    {
        if (!$this->app->initialized()) {
            $this->app->initialize();
        }
    }
}